package com.ruoyi.common.ums.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.business.entity.YytMember;
import com.ruoyi.common.business.service.YytMemberService;
import com.ruoyi.common.oms.entity.YytOmsOrder;
import com.ruoyi.common.oms.service.YytOmsOrderService;
import com.ruoyi.common.ums.entity.YytUmsGrowthChangeHistory;
import com.ruoyi.common.ums.dao.YytUmsGrowthChangeHistoryMapper;
import com.ruoyi.common.ums.entity.YytUmsIntegrationChangeHistory;
import com.ruoyi.common.ums.service.YytUmsGrowthChangeHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.ums.service.YytUmsIntegrationChangeHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
* <p>
    * 成长值变化历史记录 服务实现类
    * </p>
*
* @author MrPing
* @since 2022-06-24
*/
@Service
public class YytUmsGrowthChangeHistoryServiceImpl extends ServiceImpl<YytUmsGrowthChangeHistoryMapper, YytUmsGrowthChangeHistory> implements YytUmsGrowthChangeHistoryService {

    @Autowired
    private YytUmsGrowthChangeHistoryMapper yytUmsGrowthChangeHistoryMapper;

    @Autowired
    private YytUmsIntegrationChangeHistoryService yytUmsIntegrationChangeHistoryService;

    @Autowired
    private YytOmsOrderService yytOmsOrderService;

    @Autowired
    private YytMemberService yytMemberService;


    @Override
    public void addUserIntegral(String orderId) {
        YytOmsOrder order = yytOmsOrderService.getById(orderId);

        // 修改用户成长值
        int addIntegral =  order.getPayAmount().intValue() - order.getUseIntegration();
        UpdateWrapper<YytMember> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", order.getMemberId()).setSql("integration = " + addIntegral + " + integration, growth = growth + " + order.getPayAmount().intValue());
        yytMemberService.update(updateWrapper);

        // 添加成长值记录
        YytUmsGrowthChangeHistory history = new YytUmsGrowthChangeHistory();
        history.setMemberId(order.getMemberId());
        history.setOrderId(orderId);
        history.setChangeCount(order.getPayAmount().intValue());
        history.setNote("消费增长成长值");
        history.setSourceType(0);
        history.setCreateTime(LocalDateTime.now());
        super.save(history);

        // 添加积分记录
        YytUmsIntegrationChangeHistory changeHistory = new YytUmsIntegrationChangeHistory();
        changeHistory.setMemberId(order.getMemberId());
        changeHistory.setOrderId(orderId);
        changeHistory.setChangeCount(addIntegral);
        changeHistory.setCreateTime(LocalDateTime.now());
        changeHistory.setNote("消费增长积分");
        changeHistory.setSourceTyoe(0);
        yytUmsIntegrationChangeHistoryService.save(changeHistory);

    }
}
